package com.miaosha.controller;

import com.miaosha.error.EnumError;
import com.miaosha.error.ErrorException;
import com.miaosha.response.CommonResponse;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
public class BaseController {

    public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";


    // 定义handler解决未被controller层exception
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handlerException(HttpServletRequest httpServletRequest , Exception e){
        Map<String, Object> responseData = new HashMap<>();
        if (e instanceof ErrorException) {
            ErrorException errorException = (ErrorException) e;
            responseData.put("errorCode", errorException.getErrorCode());
            responseData.put("errorMessage", errorException.getErrorMessage());
        } else {
            responseData.put("errorCode", EnumError.UNKNOWN_ERROR.getErrorCode());
            responseData.put("errorMessage", EnumError.UNKNOWN_ERROR.getErrorMessage());
        }
        return CommonResponse.create(responseData, "failure");
    }
}
